package com.halden.mycache.support.saveStrategy.RDBSaveStrategy.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.halden.mycache.support.saveStrategy.RDBSaveStrategy.IRDBSaveMode;
import com.halden.mycache.core.IMyCache;
import com.halden.mycache.core.Impl.CacheValue;

import java.io.File;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: halden
 * @Data:2023/2/7 9:52
 * @Description:
 */
public class RdbJsonSaveModeRdb<K,V> extends RdbAbstractSaveMode<K,V> implements IRDBSaveMode<K,V> {

    private static final String charset = "UTF-8";

    @Override
    public void save(IMyCache myCache, String fileName) {
        String jsonString = getJsonString(myCache);
        saveString(jsonString, fileName);
    }

    @Override
    public Map<K, CacheValue<V>> readSave(File file, Map<K,CacheValue<V>> map) {
        String jsonString = readString(file);
        if (jsonString == null || jsonString.length() == 0){
            return null;
        }
        ConcurrentHashMap concurrentHashMap = JSON.parseObject(jsonString, ConcurrentHashMap.class);
        // 将对象进行转换添加进cache的map中
        for (Object entry : concurrentHashMap.entrySet()){
            JSONObject value = (JSONObject) ((Map.Entry) entry).getValue();
            K key = (K) (((Map.Entry) entry).getKey());
            map.put(key, value.toJavaObject(CacheValue.class));
        }
        return map;
    }

    private String getJsonString(IMyCache myCache){
        StringBuffer jsonString = new StringBuffer("{");
        StringBuilder current = new StringBuilder();
        Set<Map.Entry<K, CacheValue<V>>> entrySet = myCache.entrySet();
        for(Map.Entry<K,CacheValue<V>> entry : entrySet) {
            K key = entry.getKey();
            CacheValue<V> cacheValue = entry.getValue();
            boolean checkExpire = myCache.checkExpire(key, cacheValue);
            if (checkExpire){
                current.append(JSON.toJSONString(entry))
                        .deleteCharAt(0)
                        .deleteCharAt(current.length()-1);
                jsonString.append(current.toString()).append(',');
                current.delete(0,current.length());
            }
        }
        jsonString.deleteCharAt(jsonString.length()-1).append('}');
        return jsonString.toString();
    }
}
